package com.lei.springbootpractice.config;

import com.lei.springbootpractice.pojo.CategoryPojo;
import com.lei.springbootpractice.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分类问题诊断控制器
 * 用于诊断和解决父分类无法显示子分类的问题
 */
@RestController
@RequestMapping("/api/troubleshoot")
public class CategoryTroubleshootingController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 诊断分类数据完整性
     */
    @GetMapping("/category-diagnosis")
    public Map<String, Object> diagnoseCategoryIssues() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 1. 检查父分类数据
            List<CategoryPojo> parentCategories = categoryService.getParentCategories();
            result.put("parentCategoriesCount", parentCategories.size());
            result.put("parentCategories", parentCategories);
            
            // 2. 检查每个父分类的子分类
            Map<String, Object> subcategoryInfo = new HashMap<>();
            int totalSubcategories = 0;
            
            for (CategoryPojo parent : parentCategories) {
                List<CategoryPojo> subcategories = categoryService.getSubcategories(parent.getCategoryId());
                subcategoryInfo.put(parent.getCategoryName(), Map.of(
                    "parentId", parent.getCategoryId(),
                    "subcategoryCount", subcategories.size(),
                    "subcategories", subcategories
                ));
                totalSubcategories += subcategories.size();
            }
            
            result.put("subcategoryInfo", subcategoryInfo);
            result.put("totalSubcategories", totalSubcategories);
            
            // 3. 检查数据一致性
            List<CategoryPojo> allCategories = categoryService.getAllCategories();
            result.put("totalCategories", allCategories.size());
            
            // 4. 诊断建议
            List<String> suggestions = generateSuggestions(parentCategories.size(), totalSubcategories, allCategories.size());
            result.put("suggestions", suggestions);
            
            result.put("status", "success");
            result.put("message", "分类数据诊断完成");
            
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "诊断过程中发生错误：" + e.getMessage());
            e.printStackTrace();
        }
        
        return result;
    }

    /**
     * 测试特定父分类的子分类加载
     */
    @GetMapping("/test-subcategories/{parentId}")
    public Map<String, Object> testSubcategoryLoading(@PathVariable String parentId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查父分类是否存在
            CategoryPojo parent = categoryService.getCategoryById(parentId);
            if (parent == null) {
                result.put("status", "error");
                result.put("message", "父分类不存在，ID：" + parentId);
                return result;
            }
            
            result.put("parentCategory", parent);
            
            // 检查是否真的是父分类
            if (parent.getParentCategoryId() != null) {
                result.put("status", "warning");
                result.put("message", "指定的分类不是父分类，它的父分类ID是：" + parent.getParentCategoryId());
            }
            
            // 获取子分类
            List<CategoryPojo> subcategories = categoryService.getSubcategories(parentId);
            result.put("subcategories", subcategories);
            result.put("subcategoryCount", subcategories.size());
            
            if (subcategories.isEmpty()) {
                result.put("status", "info");
                result.put("message", "该父分类下暂无子分类");
            } else {
                result.put("status", "success");
                result.put("message", "成功加载 " + subcategories.size() + " 个子分类");
            }
            
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "测试失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return result;
    }

    /**
     * 修复分类数据问题
     */
    @PostMapping("/fix-category-issues")
    public Map<String, Object> fixCategoryIssues() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 清除缓存
            categoryService.clearCache();
            
            // 重新预热缓存
            categoryService.warmUpCache();
            
            // 重新诊断
            Map<String, Object> diagnosis = diagnoseCategoryIssues();
            
            result.put("status", "success");
            result.put("message", "已清除缓存并重新加载数据");
            result.put("diagnosis", diagnosis);
            
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "修复失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return result;
    }

    /**
     * 获取缓存状态
     */
    @GetMapping("/cache-status")
    public Map<String, Object> getCacheStatus() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取缓存信息（这里可以扩展为显示缓存的详细状态）
            result.put("status", "success");
            result.put("message", "缓存状态正常");
            result.put("cacheInfo", Map.of(
                "description", "使用内存缓存，缓存有效期5分钟",
                "operations", List.of(
                    "GET /api/troubleshoot/fix-category-issues - 清除并重新加载缓存",
                    "GET /api/categories/refresh - 刷新所有分类数据"
                )
            ));
            
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", "获取缓存状态失败：" + e.getMessage());
        }
        
        return result;
    }

    /**
     * 生成诊断建议
     */
    private List<String> generateSuggestions(int parentCount, int subcategoryCount, int totalCount) {
        List<String> suggestions = new java.util.ArrayList<>();
        
        if (parentCount == 0) {
            suggestions.add("没有找到父分类，请先添加父分类");
        } else if (parentCount > 0 && subcategoryCount == 0) {
            suggestions.add("有父分类但没有子分类，这是正常的，可以继续添加子分类");
        } else if (subcategoryCount > 0) {
            suggestions.add("分类数据正常，共有 " + parentCount + " 个父分类和 " + subcategoryCount + " 个子分类");
        }
        
        if (totalCount != (parentCount + subcategoryCount)) {
            suggestions.add("数据不一致：总分类数(" + totalCount + ") ≠ 父分类数(" + parentCount + ") + 子分类数(" + subcategoryCount + ")");
        }
        
        suggestions.add("如果前端显示有问题，请检查浏览器控制台的JavaScript错误");
        suggestions.add("可以尝试清除缓存并重新加载：POST /api/troubleshoot/fix-category-issues");
        
        return suggestions;
    }
} 